package com.ics.atable.chat.controller;

import com.ics.atable.chat.model.dto.SqlExecuteRequest;
import com.ics.atable.chat.model.dto.SqlExecuteResult;
import com.ics.atable.chat.service.DynamicSqlExecutorService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import jakarta.validation.Valid;

/**
 * 动态SQL执行控制器
 * 
 * 提供REST API接口来执行动态SQL语句
 * 支持SELECT、INSERT、UPDATE、DELETE四种操作
 * 
 * @author Chawu
 */
@Slf4j
@RestController
@RequestMapping("/api/sql")
@Tag(name = "动态SQL执行", description = "动态SQL执行相关接口")
@Validated
public class DynamicSqlController {
    
    @Autowired
    private DynamicSqlExecutorService dynamicSqlExecutorService;
    
    /**
     * 执行SQL语句
     * 
     * @param request SQL执行请求
     * @return 执行结果
     */
    @PostMapping("/execute")
    @Operation(summary = "执行SQL语句", description = "执行动态SQL语句，支持SELECT、INSERT、UPDATE、DELETE操作")
    public ResponseEntity<SqlExecuteResult> executeSql(
            @Parameter(description = "SQL执行请求参数") 
            @Valid @RequestBody SqlExecuteRequest request) {
        
        log.info("收到SQL执行请求: 数据源={}, SQL={}", request.getDataSourceName(), request.getSql());
        
        try {
            // 执行SQL
            SqlExecuteResult result = dynamicSqlExecutorService.executeSql(request);
            
            // 根据执行结果返回不同的HTTP状态码
            if (result.getSuccess()) {
                return ResponseEntity.ok(result);
            } else {
                return ResponseEntity.badRequest().body(result);
            }
            
        } catch (Exception e) {
            log.error("执行SQL时发生异常: {}", e.getMessage(), e);
            SqlExecuteResult errorResult = SqlExecuteResult.error("系统异常: " + e.getMessage());
            return ResponseEntity.internalServerError().body(errorResult);
        }
    }
    
    /**
     * 执行查询SQL（GET方式，用于简单查询）
     * 
     * @param dataSourceName 数据源名称
     * @param sql SQL语句
     * @param pageNum 页码（可选）
     * @param pageSize 每页大小（可选）
     * @return 查询结果
     */
    @GetMapping("/query")
    @Operation(summary = "执行查询SQL", description = "通过GET方式执行SELECT查询")
    public ResponseEntity<SqlExecuteResult> executeQuery(
            @Parameter(description = "数据源名称") 
            @RequestParam String dataSourceName,
            
            @Parameter(description = "SQL查询语句") 
            @RequestParam String sql,
            
            @Parameter(description = "页码，从1开始") 
            @RequestParam(required = false, defaultValue = "1") Integer pageNum,
            
            @Parameter(description = "每页大小") 
            @RequestParam(required = false, defaultValue = "10") Integer pageSize) {
        
        log.info("收到查询请求: 数据源={}, SQL={}, 页码={}, 每页大小={}", 
            dataSourceName, sql, pageNum, pageSize);
        
        try {
            // 构建请求对象
            SqlExecuteRequest request = new SqlExecuteRequest();
            request.setDataSourceName(dataSourceName);
            request.setSql(sql);
            request.setPageNum(pageNum);
            request.setPageSize(pageSize);
            
            // 执行查询
            SqlExecuteResult result = dynamicSqlExecutorService.executeSql(request);
            
            if (result.getSuccess()) {
                return ResponseEntity.ok(result);
            } else {
                return ResponseEntity.badRequest().body(result);
            }
            
        } catch (Exception e) {
            log.error("执行查询时发生异常: {}", e.getMessage(), e);
            SqlExecuteResult errorResult = SqlExecuteResult.error("系统异常: " + e.getMessage());
            return ResponseEntity.internalServerError().body(errorResult);
        }
    }
    
    /**
     * 测试数据源连接
     * 
     * @param dataSourceName 数据源名称
     * @return 测试结果
     */
    @GetMapping("/test-connection")
    @Operation(summary = "测试数据源连接", description = "测试指定数据源的连接是否正常")
    public ResponseEntity<SqlExecuteResult> testConnection(
            @Parameter(description = "数据源名称") 
            @RequestParam String dataSourceName) {
        
        log.info("收到连接测试请求: 数据源={}", dataSourceName);
        
        try {
            // 执行简单的测试查询
            SqlExecuteRequest request = new SqlExecuteRequest();
            request.setDataSourceName(dataSourceName);
            request.setSql("SELECT 1");
            
            SqlExecuteResult result = dynamicSqlExecutorService.executeSql(request);
            
            if (result.getSuccess()) {
                result.setData(null); // 清除测试数据
                result.setErrorMessage("连接测试成功");
                return ResponseEntity.ok(result);
            } else {
                return ResponseEntity.badRequest().body(result);
            }
            
        } catch (Exception e) {
            log.error("测试连接时发生异常: {}", e.getMessage(), e);
            SqlExecuteResult errorResult = SqlExecuteResult.error("连接测试失败: " + e.getMessage());
            return ResponseEntity.internalServerError().body(errorResult);
        }
    }
}
